package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.constant.GlobalConstant;
import com.heima.common.constant.ScheduleConstants;
import com.heima.model.article.dots.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;

@Transactional
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {
    @Autowired
    IScheduleClient scheduleClient;
    @Autowired
    WmNewsService wmNewsService;
    @Autowired
    WmChannelService wmChannelService;
    @Autowired
    WmUserService wmUserService;

    @Autowired
    IArticleClient articleClient;
    @Override
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务");
        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        scheduleClient.addTask(task);
    }

    @Override
    @PostConstruct
    public void scanNewsByTask() {
        Thread pullAndPublishNewsThread=new Thread(new Runnable() {
            @Override
            public void run() {
                while (true)
                {
                    pullAndPublishNews();
                }
            }
        });
        pullAndPublishNewsThread.start();
    }
    private void pullAndPublishNews()
    {
        try{
            ResponseResult result = scheduleClient.pull(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
            if (result!=null&&result.getCode().equals(GlobalConstant.OK_CODE)&&result.getData()!=null)
            {

                Task task=JSON.parseObject(JSON.toJSONString(result.getData()),Task.class);
                WmNews news = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
                log.info("执行发布"+news.getId());
                publishNews(news.getId());
            }
            else {
                try {
                    Thread.sleep(GlobalConstant.THREAD_SLEEP_TIME);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }catch (RuntimeException e){
            log.error("任务执行失败");
            e.printStackTrace();
            log.warn("schedule还未启动");
            try {
                Thread.sleep(GlobalConstant.THREAD_SLEEP_TIME);
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }

    }


    private void publishNews(Integer id)
    {
        if(id==null)
        {
            throw new RuntimeException(AppHttpCodeEnum.PARAMS_NOT_NULL.getErrorMessage());
        }
        WmNews news = wmNewsService.getById(id);
        if(news==null)
        {
            throw new RuntimeException(AppHttpCodeEnum.NEWS_NOT_EXIST.getErrorMessage());
        }
        saveOrUpdateAppArticle(news);
    }
    private void saveOrUpdateAppArticle(WmNews wmNews){

        //调用feign
        ResponseResult responseResult = articleClient.saveOrUpdateArticleAndConfig(getArticleDtoByWmNews(wmNews));
        if (!responseResult.getCode().equals(GlobalConstant.OK_CODE))
        {
//            wmNewsService.updateStatusAndReason(wmNews.getId(),WmNews.Status.SUCCESS,GlobalConstant.AUDIT_SUCCESS);
            throw new RuntimeException(GlobalConstant.SHELF_FAILURE);
        }
        Long articleId=(Long)responseResult.getData();
        wmNewsService.updateStatusAndReasonAndArticleId(wmNews.getId(),WmNews.Status.PUBLISHED,GlobalConstant.AUDIT_SUCCESS,articleId);

    }
    private ArticleDto getArticleDtoByWmNews(WmNews wmNews)
    {
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        dto.setLayout(wmNews.getType());
        WmChannel wmChannel=wmChannelService.getById(wmNews.getId());
        if (wmChannel!=null)
        {
            dto.setChannelName(wmChannel.getName());
        }
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser=wmUserService.getById(wmNews.getUserId());
        if(wmUser!=null)
        {
            dto.setAuthorName(wmUser.getName());
        }
        if (wmNews!=null)
        {
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());
        return dto;
    }
}
